import logging
from telnetlib import Telnet


# logging.basicConfig(level=logging.DEBUG)


class BaseClient:
    enter = b'\n'

    def __init__(self, *args, **kwargs):
        """初始化连接参数"""
        self._args: tuple = args
        self._kwargs: dict = kwargs
        self._device: str = kwargs.get("device")
        self._hostname: str = kwargs.get("hostname")
        self._host: str = kwargs.get("host")
        self._username: str = kwargs.get("username")
        self._password: str = kwargs.get("password")
        self._port: int = int(kwargs.get('port', 23))
        self._status: bool = False
        self._tn: Telnet | dict = self._connect()

    def __del__(self):
        """销毁对象时关闭通道"""
        try:
            if isinstance(self._tn, Telnet):
                self._tn.close()
        except Exception:
            pass

    def _response(self, data: str) -> dict:
        """统一返回值结构"""
        return dict(device=self._device, hostname=self._hostname, host=self._host, status=self._status, data=data)

    def _connect(self) -> Telnet | dict:
        """创建连接"""
        try:
            tn = Telnet(host=self._host, port=self._port, timeout=30)
            logging.info(f"正在连接：：{self._device}")
            tn.read_until(b"Username: ", timeout=1)
            tn.write(self._username.encode('ascii') + b"\n")
            tn.read_until(b"Password: ", timeout=1)
            tn.write(self._password.encode('ascii') + b"\n")
            if tn.read_until(b"Login failed!", timeout=1).decode() in "Login failed!":
                message: dict = self._response(data="登录失败")
                tn.close()
                return message
            self._screen(tn)
            return tn
        except TimeoutError:
            message: dict = self._response(data="连接超时")
            return message
        except Exception as e:
            message = self._response(data=f"异常报错{str(e)}")
            return message

    def _screen(self, tn: Telnet):
        """关闭设备分屏"""
        tn.write(b"screen-length disable" + self.enter)

    def _quit(self):
        """telnet使用关闭会话来读取通道内容"""
        self._tn.write(b"return" + self.enter)
        self._tn.write(b"quit" + self.enter)

    @property
    def get_configure(self) -> dict:
        """获取配置"""
        if not isinstance(self._tn, Telnet):
            return self._tn
        self._tn.write(b"display current-configuration" + self.enter)
        self._quit()
        data: str = self._tn.read_all().decode()
        self._status = True
        message: dict = self._response(data=data)
        return message


def run_t(*args, **kwargs) -> dict:
    """启动程序"""
    tn = BaseClient(*args, **kwargs)
    data = tn.get_configure
    return data


if __name__ == '__main__':
    pass
